package com.xm.controller;


import com.xm.common.utils.*;

import com.xm.pojo.*;
import com.xm.service.BgmService;
import com.xm.service.VideoService;

import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@Api(value = "视频业务的接口", tags = {"视频业务的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController {

    @Autowired
    private BgmService bgmService;

    @Autowired
    private VideoService videoService;


    @ApiOperation(value = "短视屏上传", notes = "短视屏上传的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "bgmId", value = "背景音乐id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoSeconds", value = "视频时长", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoWidth", value = "用户id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoHeight", value = "用户id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "desc", value = "视频描述", required = false, dataType = "String", paramType = "form")
    })
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public JSONResult uploadVideo(String userId, String bgmId,
                                  double videoSeconds, int videoWidth,
                                  int videoHeight, String desc,
                                  @ApiParam(value = "短视屏文件", required = true) MultipartFile file) throws Exception {
        //保存到数据库的文件相对路径
        String uploadPathDB = "/" + userId + "/video";
        String coverPathDB = "/" + userId + "/cover";
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        //视频文件保存的绝对路径
        String finalVideoPath = "";
        //封面文件保存得绝对路径
        String finalCoverPath = "";
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                //取文件名前缀
                String preFix = fileName.split("\\.")[0];
                coverPathDB += "/" + preFix + ".jpg";
                if (!StringUtils.isEmpty(fileName)) {
                    finalVideoPath = File_Space + uploadPathDB + "/" + fileName;
                    finalCoverPath = File_Space + coverPathDB;
                    //数据库保存的路径
                    uploadPathDB += "/" + fileName;
                    File outFile1 = new File(finalVideoPath);
                    File outFile2 = new File(finalCoverPath);
                    if (outFile1.getParentFile() != null || !outFile1.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile1.getParentFile().mkdirs();

                    }
                    if (outFile2.getParentFile() != null || !outFile2.getParentFile().isDirectory()) {
                        //创建封面的父文件夹
                        outFile2.getParentFile().mkdirs();

                    }
                    fileOutputStream = new FileOutputStream(outFile1);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return JSONResult.errorMsg("上传出错了...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错了...");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }

        if (!StringUtils.isEmpty(bgmId)) {
            Bgm bgm = bgmService.queryBgm(bgmId);
            String mp3InputPath = File_Space + bgm.getPath();
            MergeVideoMp4 tool = new MergeVideoMp4(FFMPegEXE);
            String videoInputPath = finalVideoPath;
            //合并后的视频的存储路径
            String videoOutputName = UUID.randomUUID().toString() + ".mp4";
            uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
            String videoOutputPath = File_Space + uploadPathDB;
            //合并音乐与视频
            tool.convertor(videoInputPath, mp3InputPath, videoSeconds, videoOutputPath);
        }

        //截图获取封面
        FetchVideoCover videoInfo = new FetchVideoCover("D:\\ffmpeg\\bin\\ffmpeg.exe");
        videoInfo.getCover(finalVideoPath, File_Space + coverPathDB);

        System.out.println("uploadPathDB:" + uploadPathDB);
        //封装Video对象保存到数据库
        Videos video = new Videos();
        video.setUserId(userId);
        video.setVideoPath(uploadPathDB);
        video.setVideoSeconds((float) videoSeconds);
        video.setAudioId(bgmId);
        video.setCreateTime(new Date());
        video.setVideoHeight(videoHeight);
        video.setVideoWidth(videoWidth);
        video.setVideoDesc(desc);
        video.setCoverPath(coverPathDB);
        video.setStatus(VideoStatusEnum.SUCCESS.value);

        String videoId = videoService.saveVideo(video);
        return JSONResult.ok(videoId);
    }

    @ApiOperation(value = "封面上传", notes = "短视屏封面上传的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "视频id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form")}
    )
    @PostMapping(value = "/uploadCover", headers = "content-type=multipart/form-data")
    public JSONResult uploadCover(String userId,
                                  String videoId,
                                  @ApiParam(value = "封面文件", required = true) MultipartFile file) throws Exception {
        if (StringUtils.isEmpty(videoId) || StringUtils.isEmpty(userId) || userId == "[object Undefined]") {
            return JSONResult.errorMsg("视频主键与用户主键都不能为空!");
        }
        //保存到数据库的文件相对路径
        String uploadPathDB = "/" + userId + "/cover";
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        //文件保存的绝对路径
        String finalVideoPath = "";
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                System.out.println(fileName);
                if (!StringUtils.isEmpty(fileName)) {
                    finalVideoPath = File_Space + uploadPathDB + "/" + fileName;
                    //数据库保存的路径
                    uploadPathDB += "/" + fileName;
                    File outFile = new File(finalVideoPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();

                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return JSONResult.errorMsg("上传出错了...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错了...");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        videoService.updateVideo(videoId, uploadPathDB);
        return JSONResult.ok();
    }

    /**
     * @param video
     * @param isSavedRecord 0为查询全部,1需要保存热搜词
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "按条件展示所有视频", notes = "按条件展示所有视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "video", value = "视频条件", required = true, dataType = "Videos", paramType = "body"),
            @ApiImplicitParam(name = "isSavedRecord", value = "是否查询全部,0表示查询全部", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", required = false, dataType = "String", paramType = "query")}
    )
    @PostMapping("/showAll")
    public JSONResult query(@RequestBody Videos video, Integer isSavedRecord, Integer page, Integer pageSize) throws Exception {
        if (page == null) {
            page = 1;
        }
        if (isSavedRecord == null) {
            isSavedRecord = 0;
        }

        PagedResult result = videoService.getAllVideos(video, isSavedRecord, page, PageSize);
        return JSONResult.ok(result);
    }

    @ApiOperation(value = "按条件展示喜欢的视频", notes = "按条件展示喜欢的视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", required = false, dataType = "String", paramType = "query")}
    )
    @PostMapping("/showLikeVideo")
    public JSONResult queryLikeVideo(String userId, Integer page, Integer pageSize) throws Exception {
        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult result = videoService.getLikeVideos(userId, page, pageSize);
        return JSONResult.ok(result);
    }

    @ApiOperation(value = "按条件展示关注者的视频", notes = "按条件展示关注者的视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", required = false, dataType = "String", paramType = "query")}
    )
    @PostMapping("/showFollowVideo")
    public JSONResult queryFollowVideo(String userId, Integer page, Integer pageSize) throws Exception {
        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult result = videoService.getFollowVideos(userId, page, pageSize);
        return JSONResult.ok(result);
    }


    /**
     * 热搜词查询
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "热搜词展示", notes = "热搜词展示的接口")
    @PostMapping("/hot")
    public JSONResult query() {
        List<String> hotWords = videoService.getHotWords();
        return JSONResult.ok(hotWords);
    }

    /**
     * 点赞
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "用户点击喜欢视频", notes = "用户点击喜欢视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoId", value = "视频id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoOwnId", value = "视频拥有者id", required = true, dataType = "String", paramType = "query"),
    })
    @PostMapping("/userLike")
    public JSONResult userLike(String userId, String videoId, String videoOwnId) {
        videoService.userLikeVideo(userId, videoId, videoOwnId);
        return JSONResult.ok();
    }

    /**
     * 取消点赞
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "用户点击取消喜欢视频", notes = "用户点击取消喜欢视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoId", value = "视频id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "videoOwnId", value = "视频拥有者id", required = true, dataType = "String", paramType = "query"),
    })
    @PostMapping("/userUnLike")
    public JSONResult userUnLike(String userId, String videoId, String videoOwnId) {
        videoService.userUnLikeVideo(userId, videoId, videoOwnId);
        return JSONResult.ok();
    }

    @ApiOperation(value = "保存评论", notes = "保存评论的接口")
    @ApiImplicitParam(name = "comments", value = "评论对象", required = true, dataType = "Comments", paramType = "body")
    @PostMapping("/saveComments")
    public JSONResult saveComments(@RequestBody Comments comments) {
        videoService.saveComments(comments);
        return JSONResult.ok("发布成功..");
    }

    @ApiOperation(value = "查询评论", notes = "查询评论的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "视频id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "一页多少条", required = false, dataType = "Integer", paramType = "query")}
)
    @PostMapping("/getAllComments")
    public JSONResult getAllComments(String videoId,Integer page,Integer pageSize) {
        if(page == null){
            page = 1;
        }

        if(pageSize == null){
            pageSize = 10;
        }
        PagedResult result = videoService.getAllComments(videoId,page,pageSize);
        return JSONResult.ok(result);
    }


}
